import time
from pymongo import MongoClient
from config import config

class MongoDb(object):
    def __init__(self):
        super(MongoDb, self).__init__()
        self.__connect()
    
    def __connect(self):
        try:
            self.client = MongoClient(config['MongoDb']['path'])
            self.db = self.client.Weather
        except Exception, e:
            log = Logs()
            log.logwrite('MongoDb connect failed, Python:' + e.message)

    def getCityToQuery(self):
        results = self.db.target_city.find()
        return results
        pass

    def checkWeather(self, targetRow, last_update) :
        results = self.db.weather_city_now.find_one({'city_id': targetRow["city_id"], 'updated_at': last_update})
        return results
        pass

    def insertWeatherToDb(self, city_id, result) :
        weather_now_json = {
            "city_id" : city_id, 
            "info":result, 
            "created_at":int(time.time())
        }
        self.db.weather_now.insert_one(weather_now_json)
        pass

    def closedb(self):
        self.client.close()
        pass